package com.factory.iamp.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
    //后台监控：web.xml, ServletRegistrationBean
    // 因为springBoot内置了servlet容器，所以没有web.xml，替代方法：ServletRegistionBean
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

        //配置用于登录DRUID后台的账号和密码
        HashMap<String, String> initParameters =  new HashMap<>();
        //注意：loginUsername和loginPassword这两个key是固定的，不能改名
        initParameters.put("loginUsername","iamp_admin");
        initParameters.put("loginPassword","iamp_admin");

        //allow表示ip白名单，""表示ip可访问，如果写localhost表示本地可访问
        initParameters.put("allow","localhost");

        //deny表示ip黑名单,优先级高于allow
        //initParameters.put("deny","192.168.1.123");

        //设置初始化参数
        bean.setInitParameters(initParameters);

        return bean;
    }

    //filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());

        //设置过滤的内容
        Map<String, String> initParameters =new HashMap<>();

        //排除统计以下内容
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);

        return bean;
    }
}
